﻿using System;
using System.IO;
using System.IO.Compression;

namespace MikeKappel.Com.CS
{
    public partial class Helper
    {
        /// <summary>
        /// Compression or Decompression
        /// </summary>
        public enum ZipMode
        {
            Compress,
            Decompress
        }
        /// <summary>
        /// Zip files with GZipStream 
        /// </summary>
        /// <param name="fileToRead">Name of File to Open</param>
        /// <param name="fileToWrite">Name of File to Save As</param>
        /// <param name="mode">Compression or Decompression</param>
        public static void Zip(String fileToRead, String fileToWrite, ZipMode mode)
        {
            using (Stream fileReading = File.OpenRead(fileToRead))
            using (Stream fileWriting = File.Create(fileToWrite))
            using (Stream sZip = (mode == ZipMode.Compress) 
                ? new GZipStream(fileWriting, CompressionMode.Compress) 
                : new GZipStream(fileReading, CompressionMode.Decompress))
            {
                Byte[] buffer = new byte[1024];
                Int32 nRead;
                if (mode == ZipMode.Compress)
                    while ((nRead = fileReading.Read(buffer, 0, buffer.Length)) != 0)
                        sZip.Write(buffer, 0, nRead);
                else
                    while ((nRead = sZip.Read(buffer, 0, buffer.Length)) != 0)
                        fileWriting.Write(buffer, 0, nRead);
            }
        }
    }
}
